package com.owen.oauth2.client.config;


import com.owen.oauth2.client.connect.MyOAuth2ConnectionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.social.UserIdSource;
import org.springframework.social.config.annotation.ConnectionFactoryConfigurer;
import org.springframework.social.config.annotation.EnableSocial;
import org.springframework.social.config.annotation.SocialConfigurerAdapter;
import org.springframework.social.connect.ConnectionFactory;
import org.springframework.social.connect.ConnectionFactoryLocator;
import org.springframework.social.connect.ConnectionSignUp;
import org.springframework.social.connect.UsersConnectionRepository;
import org.springframework.social.connect.mem.InMemoryUsersConnectionRepository;
import org.springframework.social.connect.web.ProviderSignInUtils;
import org.springframework.social.connect.web.SessionUserIdSource;
import org.springframework.social.security.SpringSocialConfigurer;

import java.util.Objects;

@Configuration
@EnableSocial
public class SocailConfig extends SocialConfigurerAdapter {

    @Autowired(required = false)
    private ConnectionSignUp connectionSignUp;

    @Override
    public void addConnectionFactories(ConnectionFactoryConfigurer connectionFactoryConfigurer, Environment environment) {
        connectionFactoryConfigurer.addConnectionFactory(createConnectionFactory());
    }

    @Override
    public UserIdSource getUserIdSource() {
        return new SessionUserIdSource();
    }

    public ConnectionFactory<?> createConnectionFactory() {
        MyOAuth2ConnectionFactory myOAuth2ConnectionFactory = new MyOAuth2ConnectionFactory("myOAuth2", "test", "test");
        myOAuth2ConnectionFactory.setScope("all");
        return myOAuth2ConnectionFactory;
    }

    @Bean
    public SpringSocialConfigurer springSocialConfigurer(){
        return new SpringSocialConfigurer();
    }

    @Override
    public UsersConnectionRepository getUsersConnectionRepository(ConnectionFactoryLocator connectionFactoryLocator) {
        InMemoryUsersConnectionRepository usersConnectionRepository = (InMemoryUsersConnectionRepository) super.getUsersConnectionRepository(connectionFactoryLocator);
        if(Objects.nonNull(connectionSignUp)){
            usersConnectionRepository.setConnectionSignUp(connectionSignUp);
        }
        return usersConnectionRepository;
    }

    @Bean
    public ProviderSignInUtils providerSignInUtils(ConnectionFactoryLocator connectionFactoryLocator){
        return new ProviderSignInUtils(connectionFactoryLocator,this.getUsersConnectionRepository(connectionFactoryLocator));
    }
}
